package com.demo.demo1;

import java.util.ArrayList;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.os.Build;
import android.provider.MediaStore;

public class FileSelectorActivity extends ActionBarActivity {
	
	FileSelectorFragment fileSelectorFragment;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_selector);

		if (savedInstanceState == null) {
			fileSelectorFragment = new FileSelectorFragment();
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, fileSelectorFragment).commit();
		}
	}
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.file_selector, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
		

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class FileSelectorFragment extends Fragment {
		
		private ListView listView;
		private ArrayAdapter<String> listViewadapter;

		public FileSelectorFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_file_selector,
					container, false);
			

			//init list view
			listView = (ListView) rootView.findViewById(R.id.filesListVIew);
			listViewadapter=new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_list_item_multiple_choice);
			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	        listView.setAdapter(listViewadapter);
	        listViewadapter.add("dummy1");
	    	listViewadapter.add("dummy2");
	    	listViewadapter.add("dummy3");      
	        
			
			//get the data from ACTION_SEND
			Intent intent = getActivity().getIntent();
			Bundle extras = intent.getExtras();
			String action = intent.getAction();

			// if this is from the share menu
			if (Intent.ACTION_SEND.equals(action)) {   if (extras.containsKey(Intent.EXTRA_STREAM)) {
			    // Get resource path
			    Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
			    String filename = parseUriToFilename(uri);

			    if (filename != null) {
			    	listViewadapter.add(filename);		    	
			    }
			  }
			} 
			
			
			return rootView;
		}
		
		
		//TODO remove if not needed
		private String parseUriToFilename(Uri uri) {
			  String selectedImagePath = null;
			  String filemanagerPath = uri.getPath();

			  String[] projection = { MediaStore.Images.Media.DATA };
			  Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);

			  if (cursor != null) {
			    // Here you will get a null pointer if cursor is null
			    // This can be if you used OI file manager for picking the media
			    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			    cursor.moveToFirst();
			    selectedImagePath = cursor.getString(column_index);
			  }

			  if (selectedImagePath != null) {
			    return selectedImagePath;
			  }
			  else if (filemanagerPath != null) {
			    return filemanagerPath;
			  }
			   return null;
			} 
		
		

		public void gotoPhoneSearch(View view){
			if(listView!=null && listViewadapter!=null){
				SparseBooleanArray checked = listView.getCheckedItemPositions();
		        ArrayList<String> selectedItems = new ArrayList<String>();
		        for (int i = 0; i < checked.size(); i++) {
		            int position = checked.keyAt(i);
		            if (checked.valueAt(i))
		                selectedItems.add(listViewadapter.getItem(position));
		        }
		        
		        String[] outputStrArr = new String[selectedItems.size()];
				 
		        for (int i = 0; i < selectedItems.size(); i++) {
		            outputStrArr[i] = selectedItems.get(i);
		        }		        
		        
		        Toast.makeText(getActivity(), selectedItems.toString(), Toast.LENGTH_SHORT).show();
		 		       
		        Intent intent = new Intent(getActivity(),
		                PhoneSelectActivity.class);
		        Bundle b = new Bundle();
		        b.putStringArray("selectedItems", outputStrArr);
		        intent.putExtras(b);
		        startActivity(intent);
			}
		}		
	}

	public void gotoPhoneSearchOnClick(View view){
		if(fileSelectorFragment!=null){
			fileSelectorFragment.gotoPhoneSearch(view);
		}
	}

}
